import 'package:pornhub_app/http/http_service.dart';
import 'package:pornhub_app/model/user/user_info_model.dart';
import 'package:get/get.dart';
import 'package:pornhub_app/utils/save_account_dialog.dart';

import '../../../../components/easy_toast.dart';
import '../../../../http/api/api.dart';
import '../../../../model/mine/share_link_model.dart';
import '../../../../services/storage_service.dart';
import '../../../../services/user_service.dart';
import '../../../../utils/loading_dialog.dart';

class LoginRegisterController extends GetxController {
  final storageService = Get.find<StorageService>();
  final us = Get.find<UserService>();
  var url = ''.obs;

  @override
  void onInit() {
    _getSharedLink();
  }

  Future postLogin(String account, String password) async {
    showCustomDialog(Get.context!, "登录中,请稍候..");
    try {
      final u = await httpInstance.post(
          url: 'user/account/login',
          body: {
            'account': account.trim(),
            'password': password.trim(),
          },
          complete: UserInfo.fromJson);
      if (u is UserInfo) {
        EasyToast.show("登录成功");
        storageService.setToken(u.token!);
        // us.updateAPIUserInfo();
      }
      Get.back();
    } catch (_) {}
    closeDialog(Get.context!);
  }

  Future postRegister(String account, String pwd) async {
    showCustomDialog(Get.context!, "注册中,请稍候..");
    try {
      final resp = await httpInstance.post(
          url: 'user/register',
          body: {
            "account": account.trim(),
            "password": pwd.trim(),
          },
          complete: UserInfo.fromJson);
      if (resp is UserInfo) {
        storageService.setToken(resp.token!);
        storageService.saveRegisterPassword(pwd.trim());
        EasyToast.show("注册成功");
      }
    } catch (_) {}
    closeDialog(Get.context!);
    saveAccountDialog(Get.context!, account, pwd, true, url.value);
  }

  Future _getSharedLink() async {
    try {
      final result = await Api.getShareLink();
      if (result is ShareRespModel) {
        url.value = result.url ?? '';
      }
    } catch (e) {
      return null;
    }
  }

  String getMainDomainFromUrl() {
    Uri uri = Uri.parse(url.value);
    if (url.value.isEmpty) return '';
    return uri.host.split('.').length > 2
        ? '${uri.scheme}://${uri.authority}'
        : '${uri.scheme}://${uri.host}';
  }
}
